package server;

import gms.ILookupTable;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.List;
import java.util.Map;

import network.MessageService;

import cache.CacheDb;
import cache.ICache;

import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;

import server.CommandFactories.CmdType;
import command.ICommand;
import command.IResponse;
import command.protobuf.GetMultiUserHomeTimelineCmdArgsUtil.*;
import command.protobuf.MessageBufProtoBuf.RpcMessage;

public class ServerGetMultiUserTimelineCommand implements ICommand {
	public static final CmdType cmdType = CmdType.getusertimeline;

	RpcMessage originMessage = null;
	private Socket socket;

	@Override
	public RpcMessage invoke() {
		try {
			GetMultiUserHomeTimelineCmdArgs args = GetMultiUserHomeTimelineCmdArgs
					.parseFrom(originMessage.getContent().toByteArray());
			
			GetMultiUserHomeTimelineResponse.Builder retBuilder = GetMultiUserHomeTimelineResponse.newBuilder();
			ICache cache = CacheDb.getInstance().getCache(args.getDb());
			Map<String, List<String>> ret = cache.getMultipleTopk(args.getUidList(), args.getStartList(), args.getTopk());
			
			for (String uid : ret.keySet()) {
				SingleUserHomeTimelineResponse.Builder singleBuilder = SingleUserHomeTimelineResponse.newBuilder();
				singleBuilder.addAllTweet(ret.get(uid));
				singleBuilder.setUid(uid);
				retBuilder.addUnits(singleBuilder.build());
			}
			
			IResponse response = CommandFactories.getCommand(cmdType)
					.createResponse();
			response.set(retBuilder.build());
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			response.write(output);
			ByteString bString = ByteString.copyFrom(output.toByteArray());
			int flag = MessageService.RESPONSE_FLAG
					| (originMessage.getHeader().getFlag() & MessageService.CLIENT_SERVER_COMM);

			RpcMessage.Header header = RpcMessage.Header.newBuilder().setID(originMessage.getHeader().getID())
					.setCmdType(cmdType.ordinal()).setFlag(flag).build();
			RpcMessage message = RpcMessage.newBuilder().setContent(bString)
					.setHeader(header).build();
			
			return message;
			
		} catch (InvalidProtocolBufferException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public CmdType getCommandType() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setOrigin(RpcMessage origin, Socket socket) {
		// TODO Auto-generated method stub

	}

}
